package com.uh.microservice.core.util;

import com.uh.microservice.core.CONSTANTS;
import com.uh.microservice.core.spring.SpringUtil;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by liming on 2017/9/26.
 */
public class FileUtil {
    public static String readTxt(String path){
        File file=new File(path);
        return readTxt(file);
    }

    public static String readTxt(File file){
        try{
            if(file.isFile() && file.exists()){
                InputStreamReader read = new InputStreamReader( new FileInputStream(file), CONSTANTS.UTF8);
                BufferedReader bufferedReader = new BufferedReader(read);
                StringBuffer buffer = new StringBuffer();
                String lineTxt="";
                while((lineTxt = bufferedReader.readLine()) != null){
                    buffer.append(lineTxt).append("\n");
                }
                read.close();

                return buffer.toString();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static List<File> ls(String path,String ext){
        File dir=new File(path);
        List<File> list=new ArrayList<File>();
        if(dir.isDirectory()) {

            File[] dirs = dir.listFiles();

            for(int i = 0;i < dirs.length ; i++){
                File subItem = dirs[i];
                if(subItem.isFile())
                    continue;
                list.addAll(ls(subItem.getPath(),ext));
            }
            File[] files = dir.listFiles(new FileFilter() {
                public boolean accept(File file) {
                    if (ext != null && StringUtils.endsWithIgnoreCase(file.getName(), ext))
                        return true;
                    return false;
                }
            });
            list.addAll(Arrays.asList(files));
        }

        return list;
    }

    public static File createFile(String filename,byte[] bytes){
        try {
            String pth=(new File(filename)).getAbsolutePath();
            String temp[] = pth.split("\\\\");
            if(temp.length==1)
                temp=pth.split("/");
            String path="";
            for(int i=0;i<temp.length-1;i++){
                path+=temp[i]+"/";
            }
            File file =new File(path);
            if(!file.exists()) file.mkdirs();
            OutputStream out = new FileOutputStream(filename);
            out.write(bytes);
            out.flush();
            out.close();
            return new File(filename);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String downloadNet(String netUrl,String fileName){
        try {
            String path= SpringUtil.getProp("file.uploadPath") + FileUploadUtil.getSaveFilePath();
            FileUploadUtil.checkFolder(path);
            URL url=new URL(netUrl);
            URLConnection conn=url.openConnection();
            InputStream inStream=conn.getInputStream();
            FileOutputStream fs=new FileOutputStream(path+fileName);

            byte[] buffer=new byte[1024];
            int byteread=0;int bytesum=0;
            while((byteread=inStream.read(buffer)) != -1){
                bytesum += byteread;
                fs.write(buffer,0,byteread);
            }
            fs.flush();
            fs.close();
            return path+fileName;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void unzipFile(String fileName,String path){
        try{
            ZipFile zip=new ZipFile(fileName, Charset.forName("GBK"));
            Enumeration enu=zip.entries();
            while(enu.hasMoreElements()){
                ZipEntry entry=(ZipEntry)enu.nextElement();
                if(entry.isDirectory()){
                    new File(path+entry.getName()).mkdirs();
                    continue;
                }
                BufferedInputStream bis=new BufferedInputStream(zip.getInputStream(entry));
                File file =new File(path+entry.getName());
                File parent=file.getParentFile();
                if(parent!=null && !parent.exists())
                    parent.mkdirs();

                FileOutputStream fos=new FileOutputStream(file);
                BufferedOutputStream bos=new BufferedOutputStream(fos,2048);
                int count;byte data[]=new byte[2048];
                while((count=bis.read(data,0,2048))!=-1)
                    bos.write(data,0,count);
                bos.flush();
                bos.close();
                bis.close();
            }
            zip.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    public static String unzip2CureentFolder(String fileName){
        String path = StringUtils.substringBeforeLast(fileName,".zip");
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")){
           unzipFile(fileName,path+"\\");
        } else {
           unzipFile(fileName,path+"/");
        }
        return path;
    }

    public static String findFileByName(String folder,String name){
        String fileName="";
        File dir=new File(folder);
        if(!dir.exists() || !dir.isDirectory()) return "";

        File[] files=dir.listFiles();
        for(int i=0;i<files.length;i++){
            File subFile=files[i];
            if(subFile.isDirectory()){
                fileName=findFileByName(subFile.getAbsolutePath(),name);
                if(!StringUtils.isBlank(fileName)) break;
            }else{
                String subName=subFile.getName();
                if(StringUtils.contains(subName,name)){
                    fileName=subFile.getAbsolutePath();
                    break;
                }
            }
        }

        return fileName;
    }

    public static List findFileExist(String folder,String name){
        List fList=new ArrayList();
        File dir=new File(folder);
        if(!dir.exists() || !dir.isDirectory()) return new ArrayList();

        File[] files=dir.listFiles();
        for(int i=0;i<files.length;i++){
            File subFile=files[i];
            if(subFile.isDirectory()){
                fList.addAll(findFileExist(subFile.getAbsolutePath(),name));
            }else{
                String subName=subFile.getName();
                if(!StringUtils.contains(subName,name)){
                    fList.add( subFile.getAbsolutePath() );
                }
            }
        }

        return fList;
    }

}
